package com.frcdi.qms.listener;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.frcdi.qms.common.core.domain.entity.SysUser;
import com.frcdi.qms.domain.Cc;
import com.frcdi.qms.service.CcService;
import com.frcdi.qms.utils.SpringContextHolder;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.engine.impl.el.FixedValue;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LoveMyOrange
 * @create 2022-10-15 19:47
 */
public class CcListener implements JavaDelegate {
    FixedValue ccUser;
    @Resource
    private RepositoryService repositoryService;
    @Override
    public void execute(DelegateExecution execution) {
        CcService ccService = SpringContextHolder.getBean(CcService.class);
        String currentActivityId = execution.getCurrentActivityId();
        List<String> selectUsers = (List<String>) execution.getVariable(currentActivityId);
        List<Cc> ccs= new ArrayList<>();
        if(CollUtil.isNotEmpty(selectUsers)){

            for (String selectUser : selectUsers) {
                Cc cc = new Cc();
                cc.setId(IdWorker.getIdStr());
                cc.setUserId(Long.valueOf(selectUser));
                cc.setProcessInstanceId(execution.getProcessInstanceId());
                ccs.add(cc);
            }
        }

        Object value = ccUser.getValue(execution);
        if(value!=null){
            List<SysUser> userInfos = JSONObject.parseObject((String) value, new TypeReference<List<SysUser>>() {
            });
            for (SysUser userInfo : userInfos) {
                Cc cc = new Cc();
                cc.setId(IdWorker.getIdStr());
                cc.setUserId(Long.valueOf(userInfo.getUserId()));
                cc.setProcessInstanceId(execution.getProcessInstanceId());
                ccs.add(cc);
            }

        }
        if(CollUtil.isNotEmpty(ccs)){
            ccService.saveBatch(ccs);
        }


    }
}
